using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Xml;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;



namespace ACM.cmsarea08.Administration.Core {
	public partial class ConfigurazioneS :  BaseEditPage {
		//protected itareanet.cmsarea08.Administration.Controls.MainButton adm_buttons;
		
		
		override protected void OnInit(EventArgs e)
		{
			if(ACM.cmsarea08.Users.CurrentUser.Role.Score>400)
				Response.Redirect("/loginadm.aspx?returnurl="+
								HttpUtility.UrlEncode(Request.ServerVariables["SCRIPT_NAME"].ToString()+
				                                        (Request.ServerVariables["QUERY_STRING"].ToString()==""?"":"?"+Request.ServerVariables["QUERY_STRING"].ToString()))
	);
			else if(ACM.cmsarea08.Users.CurrentUser.Role.Score>0)
				Response.Redirect("/administration/accessdeny.aspx");
			base.OnInit(e);
			InitializeComponent();
			
			
			
		}
		const string DBActionTable = "mainconf";
		private string _ItemID;
		private string admlogo = "";
		public bool InsertMode {
			get {
				if(Request.QueryString["new"]==null)
					return false;
				else if( Request.QueryString["new"].ToString()=="1")
					return true;
				else
					return false;
			}
		}
//		public string ItemID {
//				get { return _ItemID;				}
//				set { _ItemID = value; }
//			}
		
		protected DBClass dclass = new DBClass();
		protected ACM.cmsarea08.Function.TextClass tClass = new ACM.cmsarea08.Function.TextClass();
		private void InitializeComponent()
		{
//			if(this.Master is itareanet.cmsarea08.Administration.Core.ListerPrivate) {
//
//			}
			_ItemID = Request.QueryString["idf"]!=null?Request.QueryString["idf"].ToString():"0";
			if(adm_buttons!=null) {
				adm_buttons.StandardForm = false;
				NonStandardForm nsfOggettoForm = new NonStandardForm();
				nsfOggettoForm.Titolo = (rm.GetString("confsito"));
				nsfOggettoForm.FormName = "config";
				nsfOggettoForm.XmlPath = "/administration/edit_form/config";
				//opzionale:
				nsfOggettoForm.XslPath = "";
				/* questo blocco va impostato solo se siamo in MODIFICA, previa query a DB */
				nsfOggettoForm.DbTable = "contenuti_manager"; // un sieabbi a nianti
				nsfOggettoForm.KeyField = "colonna chiave per la where"; // un sieabbi a nianti
				//pezzo lettura params da db - se update
				nsfOggettoForm.FormData = null;
				string datains = "-";
				string datamod = "-";
				string footer = "&nbsp;"; //
				nsfOggettoForm.Footer = footer;
				//Assegnazione delle Cose alla pulsanteria:
				//verifica parametri da DB se non presenti prepara il DS.
				DataSet config =null;
				
				config = dclass.Helper_Dataset("select nomeportale, autore, metadesc, metacontent, " +
				                               "erroremessaggio, offsetdata, " +
				                               "modellolingua, if(status='1','true','false') as status, applock as lockapp, " +
				                               "favicon, AdmMail, NoReplyMail, if(RevMode='1','true','false') as RevMode, " +
				                               "if(ContentRoleFilter='1','true','false') as ContentRoleFilter, AdmLogo " +
				                               "from " +
					                            ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + DBActionTable + 
					                           " where nomeapplicazione='" + mainconfiguration.MainConf.NomeApplicazione +"' limit 1 ;");
				if(config==null) {
					//inizializza DS
					config = new DataSet();
					config.Tables.Add(new DataTable());
					config.Tables[0].Columns.Add(new DataColumn("nomeportale"));
					config.Tables[0].Columns.Add(new DataColumn("autore"));
					config.Tables[0].Columns.Add(new DataColumn("metadesc"));
					config.Tables[0].Columns.Add(new DataColumn("metacontent"));
					config.Tables[0].Columns.Add(new DataColumn("erroremessaggio"));
					config.Tables[0].Columns.Add(new DataColumn("offsetdata"));
					config.Tables[0].Columns.Add(new DataColumn("modellolingua"));
					config.Tables[0].Columns.Add(new DataColumn("status"));
					config.Tables[0].Columns.Add(new DataColumn("lockapp"));
					config.Tables[0].Columns.Add(new DataColumn("favicon"));
					config.Tables[0].Columns.Add(new DataColumn("admmail"));
					config.Tables[0].Columns.Add(new DataColumn("noreplymail"));
					config.Tables[0].Columns.Add(new DataColumn("revmode"));
					config.Tables[0].Columns.Add(new DataColumn("contentrolefilter"));
					DataRow dr = config.Tables[0].NewRow();
					dr[0] = mainconfiguration.MainConf.NomePortale;
					dr[1] = mainconfiguration.MainConf.Autore;
					dr[2] = mainconfiguration.MainConf.MetaDesc;
					dr[3] = mainconfiguration.MainConf.MetaContent;
					dr[4] = mainconfiguration.MainConf.ErroreMessaggio;
					dr[5] = mainconfiguration.MainConf.OffSetData;
					dr[8] = (mainconfiguration.MainConf.WebSiteLock==true?"1":"0");//lockapp
					dr[10] = mainconfiguration.MainConf.AdministratorEmailAddress;
					dr[11] = mainconfiguration.MainConf.NoReplyEmailAddress;
					dr[12] = mainconfiguration.MainConf.RevMode;
					dr[13] = mainconfiguration.MainConf.ApplyContentFilter;
//					dr[6] = rm.GetString("def_ml" + mainconfiguration.MainConf.ModelloLingua.ToString());
					int ml_count=0;
					foreach(string it in Enum.GetNames(typeof(LanguageModel)) ) {
		//	        	if(ml==rm.GetString("def_ml" + it)) {
						if(it==mainconfiguration.MainConf.ModelloLingua.ToString()) {
			        		break;
			        	}
						ml_count++;
					}	
					dr[6] = ml_count.ToString();
					dr[7] = mainconfiguration.MainConf.Status;
					dr[8] = (mainconfiguration.MainConf.Favicon.ToLower()=="/template/favicon.ico"?"":mainconfiguration.MainConf.Favicon);
					config.Tables[0].Rows.Add(dr);
				} else {
					
					if(config.Tables[0].Rows[0]["modellolingua"]!=null) {
						int ml_count=0;
						foreach(string it in Enum.GetNames(typeof(LanguageModel)) ) {
			//	        	if(ml==rm.GetString("def_ml" + it)) {
							if(it==mainconfiguration.MainConf.ModelloLingua.ToString()) {
				        		break;
				        	}
							ml_count++;
						}							
						config.Tables[0].Rows[0]["modellolingua"] = ml_count.ToString(); 
//							 rm.GetString("def_ml" +config.Tables[0].Rows[0]["modellolingua"].ToString());
					}
					if(config.Tables[0].Rows[0]["admlogo"]!=null){
						admlogo=config.Tables[0].Rows[0]["admlogo"].ToString();
					}
				}
				FormDataAdapter fda = new FormDataAdapter();
//				string temp = fda.DataSetToItanData(config).ToString();
//				Response.Write(temp);
				nsfOggettoForm.FormData = config!=null?fda.DataSetToItanData(config):null;
				
				adm_buttons.SaveFormClicked += new SaveFormEventHandler(EVENTOSALVA);
				adm_buttons.IsLockable = false;
				adm_buttons.NSFormData = nsfOggettoForm;
			}
			//adm_buttons.CaricaLayoutForm();
			this.Load += new System.EventHandler(this.Page_Load);
			
		}
	
		private void Page_Load(object o , EventArgs e) {
			if(!ACM.cmsarea08.Users.CurrentUser.isRuolo("SysAdm")){
//				Response.Redirect("http://" + Request.ServerVariables["SERVER_NAME"]+"/administration/login.aspx");
			}
			_ItemID = Request.QueryString["idf"]!=null?Request.QueryString["idf"].ToString():"0";
			if(!Page.IsPostBack) {
				
			}
		}
		public void EVENTOSALVA(object o, SaveFormEventArgs e) {
			//devo salvare.
			// e.FormData
			// e.CommandType
			string query = "";
			XmlDocument xdoc = new XmlDocument();
			if(e.FormData!=null) {
				FormDataAdapter fda = new FormDataAdapter();
				xdoc = fda.ObjectToXmlDocument(e.FormData);
			} else {
				this.PrintMessage(rm.GetString("error_no_data_upd"));
				return;
			}
			if(xdoc==null){
				this.PrintMessage(rm.GetString("error_no_data_upd"));
				return;
			}
			
			//inizia verifica dei dati.
			//dati possibili:
			string nomep = "";
			string autore = "";
			string md = "";
			string mp = "";
			string emsg = "";
			string ofd = "";
			string ml = "";
			string st = "";
			string locksite = "0";
			string favicon = "";
			string admemail = "";
			string noreplyemail = "";
			string revmode = "";
			string contentrolefilter = "";
			string admilogo="";
			
			XmlNode temp = null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"nomeportale\"]/valore");
			if(temp!=null)
				nomep = HttpUtility.HtmlEncode(temp.InnerText);
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"autore\"]/valore");
			if(temp!=null)
				autore = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"metadesc\"]/valore");
			if(temp!=null)
				md = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"metacontent\"]/valore");
			if(temp!=null)
				mp = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"erroremessaggio\"]/valore");
			if(temp!=null)
				emsg = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"offsetdata\"]/valore");
			if(temp!=null)
				ofd = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"modellolingua\"]/valore");
			if(temp!=null)
				ml = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"status\"]/valore");
			if(temp!=null)
				st = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"lockapp\"]/valore");
			if(temp!=null)
				locksite = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"favicon\"]/valore");
			if(temp!=null)
				favicon = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"admlogo\"]/valore");
			if(temp!=null)
				admilogo = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"AdmMail\"]/valore");
			if(temp!=null)
				admemail = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"NoReplyMail\"]/valore");
			if(temp!=null)
				noreplyemail = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"RevMode\"]/valore");
			if(temp!=null)
				revmode = temp.InnerText;
			temp=null;
			temp = xdoc.DocumentElement.SelectSingleNode("//impostazioni/set[nome=\"ContentRoleFilter\"]/valore");
			if(temp!=null)
				contentrolefilter = temp.InnerText;
			temp=null;
			
			//verifiche:
			if(nomep=="")
				nomep = mainconfiguration.MainConf.NomePortale;
			if(autore=="")
				autore = mainconfiguration.MainConf.Autore;
			if(md == "")
				md = mainconfiguration.MainConf.MetaDesc;
			if(mp == "")
				mp = mainconfiguration.MainConf.MetaContent;			
			if(emsg == "")
				emsg = mainconfiguration.MainConf.ErroreMessaggio;			
			if(ofd == "")
				ofd = mainconfiguration.MainConf.OffSetData;			
			if(ml == "")
				ml = mainconfiguration.MainConf.ModelloLingua.ToString();
			if(st == "")
				st = mainconfiguration.MainConf.Status.ToString();	
			if(admemail=="")
				admemail = mainconfiguration.MainConf.AdministratorEmailAddress;
			if(noreplyemail=="")
				noreplyemail = mainconfiguration.MainConf.NoReplyEmailAddress;
			if(revmode=="")
				revmode = mainconfiguration.MainConf.RevMode.ToString();
			if(contentrolefilter=="")
				contentrolefilter = mainconfiguration.MainConf.ApplyContentFilter.ToString();
			
			//manda la query:
			if(nomep!=mainconfiguration.MainConf.NomePortale)
				mainconfiguration.MainConf.NomePortale = tClass.SqlTesto(nomep);
			if(autore!=mainconfiguration.MainConf.Autore)
				mainconfiguration.MainConf.Autore = autore;
			if(md!=mainconfiguration.MainConf.MetaDesc)
				mainconfiguration.MainConf.MetaDesc = md;
			if(mp!=mainconfiguration.MainConf.MetaContent)
				mainconfiguration.MainConf.MetaContent = mp;			
			if(emsg!=mainconfiguration.MainConf.ErroreMessaggio)
				mainconfiguration.MainConf.ErroreMessaggio = emsg;	
			if(ofd!=mainconfiguration.MainConf.OffSetData)
				mainconfiguration.MainConf.OffSetData = ofd;		
			if(noreplyemail!=mainconfiguration.MainConf.NoReplyEmailAddress)
				mainconfiguration.MainConf.NoReplyEmailAddress = noreplyemail;
			if(admemail!=mainconfiguration.MainConf.AdministratorEmailAddress)
				mainconfiguration.MainConf.AdministratorEmailAddress = admemail;
			if(st!=mainconfiguration.MainConf.Status.ToString())
				mainconfiguration.MainConf.Status = Convert.ToBoolean(st);
			
			if(favicon!=mainconfiguration.MainConf.Favicon.ToString())
				mainconfiguration.MainConf.Favicon = favicon;
			
			bool test = false;
			test = (locksite=="1"?true:false);
			if(test!=mainconfiguration.MainConf.WebSiteLock)
				mainconfiguration.MainConf.WebSiteLock = test;
			test = false;
			test = (revmode.ToLower()=="true"?true:false);
			if(test!=mainconfiguration.MainConf.RevMode)
				mainconfiguration.MainConf.RevMode = test;
			test = false;
			test = (contentrolefilter.ToLower()=="true"?true:false);
			if(test!=mainconfiguration.MainConf.ApplyContentFilter)
				mainconfiguration.MainConf.ApplyContentFilter = test;
			//prepara ML 
			int count=0;
			foreach(string it in Enum.GetNames(typeof(LanguageModel)) ) {
//	        	if(ml==rm.GetString("def_ml" + it)) {
				if(ml==count.ToString()) {
	        		ml = it;break;
	        	}
				count++;
			}
			if(ml!=mainconfiguration.MainConf.ModelloLingua.ToString()){
				if(Enum.IsDefined(typeof(LanguageModel),ml)) 
					mainconfiguration.MainConf.ModelloLingua = (LanguageModel)Enum.Parse(typeof(LanguageModel),
					                                                                     ml,true);
			}
			if(admlogo.Trim()!=admilogo.Trim()){
//				HttpContext.Current.Response.Write("aggiorno il logo da: \"" + admlogo + "\" a \"" + admilogo + "\"");
				dclass.ExecuteScalar("update " + dclass.TablePrefix+"mainconf set admlogo='" + admilogo + "' " +
				                     "where nomeapplicazione='" + mainconfiguration.MainConf.NomeApplicazione + "' limit 1;");
			}
//			else
//				HttpContext.Current.Response.Write("non aggiorno (\"" + admlogo + "\" == \"" + admilogo + "\")");
		
			this.PrintMessage(rm.GetString("data_upd_succ"));
			
		}
		
		
	}
	
}
